"""
@File    : ens_instance_sdg_monitor.py
@Author  : timo.tan
@Time    : 2025/07/24 18:31 
"""
import sys
import json
import time
import datetime
from typing import List
from alibabacloud_ens20171110.client import Client as Ens20171110Client
from alibabacloud_credentials.client import Client as CredentialClient, Config
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ens20171110 import models as ens_20171110_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

from tools.log_util import INFO


class EnsInstanceMonitor:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> Ens20171110Client:
        """
        使用凭据初始化账号Client
        @return: Client
        @throws Exception
        """
        # SIT 环境
        # credentialsConfig = Config(
        #     type="access_key",
        #     access_key_id="LTAI5tSN4cEk4FzE9hBxk88x",
        #     access_key_secret="ZhRlXyhuxNSpF9bSqNmOXlWr3Vav9D",
        # )

        #UAT 环境
        credentialsConfig = Config(
            type="access_key",
            access_key_id="LTAI5tPknNicjk1km64yEPvn",
            access_key_secret="8FMOyIzymGTPEYUufZULlcw62dlTUt",
        )
        # 使用AK 初始化Credentials Client。
        credentialClient = CredentialClient(credentialsConfig)

        config = open_api_models.Config(credential=credentialClient)
        config.endpoint = "ens.aliyuncs.com"
        return Ens20171110Client(config)

    @staticmethod
    def format_response(response, instance_id):
        """
        Format the API response for better readability while showing ALL fields
        """
        response_map = response.to_map()
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 创建边框
        border = "+" + "-" * 80 + "+"
        
        # 标题和基本信息部分
        formatted_output = [
            border,
            "|" + "ENS INSTANCE MONITOR REPORT".center(80) + "|",
            border,
            f"| Time: {now}",
            f"| Instance ID: {instance_id}",
            border
        ]
        
        # 1. 添加headers部分
        headers = response_map.get("headers", {})
        if headers:
            formatted_output.append("\n" + "HEADERS".center(80, "="))
            for key, value in headers.items():
                formatted_output.append(f"{key}: {value}")
        
        # 2. 添加状态码
        formatted_output.append("\n" + "STATUS".center(80, "="))
        formatted_output.append(f"Status Code: {response_map.get('statusCode', '')}")
        
        # 3. 添加body所有字段
        body = response_map.get("body", {})
        if body:
            formatted_output.append("\n" + "BODY".center(80, "="))
            
            # 展示每个body字段
            for key, value in body.items():
                if key == "DeploymentStatus" and isinstance(value, list):
                    formatted_output.append(f"\n{key}:")
                    if value:  # 如果有数据
                        for i, item in enumerate(value, 1):
                            formatted_output.append(f"  Item {i}:")
                            for k, v in item.items():
                                formatted_output.append(f"    {k}: {v}")
                            if i < len(value):
                                formatted_output.append("  " + "-" * 40)
                    else:
                        formatted_output.append("  No deployment status data")
                else:
                    formatted_output.append(f"{key}: {value}")
        
        # 结束边框
        formatted_output.append("\n" + border)
        
        return "\n".join(formatted_output)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        instance_id = args[0]
        client = EnsInstanceMonitor.create_client()
        describe_instance_sdgstatus_request = (
            ens_20171110_models.DescribeInstanceSDGStatusRequest(instance_id)
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            response: ens_20171110_models.DescribeInstanceSDGStatusResponse = (
                client.describe_instance_sdgstatus_with_options(
                    describe_instance_sdgstatus_request, runtime
                )
            )
            formatted_output = EnsInstanceMonitor.format_response(response, instance_id)
            INFO.logger.info(formatted_output)
            
            # For debugging, uncomment this to see the full response
            # INFO.logger.debug(json.dumps(response.to_map(), ensure_ascii=True, indent=4))

        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            # 诊断地址
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)


if __name__ == "__main__":
    INFO.logger.info(sys.argv)
    while True:
        # EnsInstanceMonitor.main(sys.argv[1:])
        # EnsInstanceMonitor.main(["aic-54eq14cetsyk3ykap1anugn65-1"])
        # EnsInstanceMonitor.main(["aic-vr3g24a060x011-3-04-3-ofxbycyc"]) # 195828 的实例
        EnsInstanceMonitor.main(["aic-55kk9tbzjcnbfigv4x1n0ugyo-0"]) # 355134 的实例

        time.sleep(50)

        # old = 'sdg-fb73b27d7862a54d220dc8db073f9704'
        # old = 'sdg-cacb7fef75b56344cce38f84e2078cde'

        # new = 'sdg - 28f1ecfa50e2695e21329f647100a639'

